package com.example.springsecuritydemo.security;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2021-06-24 下午4:18
 */
@Component
public class Sha256PasswordEncoder implements PasswordEncoder {
    private static final String SEPARATOR = "_";

    /**
     * rawPassword = password_salt
     *
     * @param rawPassword
     * @return
     */
    @Override
    public String encode(CharSequence rawPassword) {
        final String[] split = rawPassword.toString().split(SEPARATOR);
        return split.length > 1 ? SHA256Util.sha256(split[0], split[1]) : SHA256Util.sha256(rawPassword.toString(), null);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        final String[] split = encodedPassword.split(SEPARATOR);
        if (split.length > 1) {
            return split[0].equals(encode(rawPassword + SEPARATOR + split[1]));
        }
        return encodedPassword.equals(encode(rawPassword));
    }
}
